package com.zhiwei.msf.gateway.config;

import com.zhiwei.msf.gateway.constants.GatewayConstant;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collection;


/**
 * 自定义决策管理器
 */
@Component
public class GatewayAccessDecisionManager implements AccessDecisionManager {

    /**
     * @param authentication   已认证数据
     * @param object           授权对象，例如网络路径
     * @param configAttributes 授权对象配置规则集合(SecurityMetadataSource 定义)
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {

        //URL访问无需授权则直接通过，例如：白名单
        if (CollectionUtils.isEmpty(configAttributes)) {
            return;
        }

        //判断认证用户配置权限和资源自身权限是否匹配
        for (ConfigAttribute configAttribute : configAttributes) {
            String needPermission = configAttribute.getAttribute();
            if (GatewayConstant.WHITE_LIST_ROLE.equals(needPermission)) {
                return;
            }
            for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
                if (needPermission.trim().equalsIgnoreCase(grantedAuthority.getAuthority())) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("no permission");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}